package com.lingx.web.api.impl;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.lingx.model.impl.DefaultEntity;
import com.lingx.service.LingxService;
import com.lingx.service.ModelService;
import com.lingx.web.api.IApi;
@Component
public class Api9028 extends AbstractDevApi implements IApi{
	@Resource
	private LingxService lingxService;
	
	@Resource
	private ModelService modelService;
	@Override
	public int getApiCode() {
		return 9028;
	}
	@Override
	public String getApiName() {
		return "提交模型";
	}
	@Override
	public Map<String, Object> api(Map<String, Object> params) {
		Map<String,Object> ret=IApi.getRetMap(1, "操作成功");
		String ecode=IApi.getParamString(params, "ecode", "");
		String url=this.lingxService.getConfigValue("lingx.update.submit.url", "none");
		DefaultEntity entity=this.modelService.getEntity(ecode);
		byte[] buff=toByteArray(entity);
		Map<String,Object> req=new HashMap<>();

		req.put("apicode",8009 );
		req.put("model",bytesToHex(buff) );
		req.put("secret",this.lingxService.getConfigValue("lingx.update.submit.secret", "none") );
		//System.out.println(JSON.toJSONString(req));
		System.out.println("提交更新模型:"+url);
		String res=post(url, JSON.toJSONString(req));
		System.out.println(res);
		return ret;
	}
	public static byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray ();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

	public static Object toObject(byte[] bytes) {
        ByteArrayInputStream bos = new ByteArrayInputStream(bytes);
        try {
            ObjectInputStream oos = new ObjectInputStream(bos);
            Object obj= oos.readObject();
            oos.close();
            bos.close();
            bytes=null;
            return obj;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
	public static String bytesToHex(byte[] b, int len) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < len; i++) {
			sb.append(toHex(b[i]));
		}
		b=null;
		return sb.toString();
	}
	public static String bytesToHex(byte[] b) {
		return bytesToHex(b,b.length);
	}

	public static final byte[] hexToBytes(String s) {
		String temp = "0123456789ABCDEF";
		byte array[] = s.toUpperCase().getBytes();
		byte[] newArr = new byte[array.length / 2];
		int index = 0;
		for (int i = 0; i < array.length; i += 2) {
			Integer t1 = temp.indexOf((char) array[i]);
			t1 = t1 << 4;
			t1 += temp.indexOf((char) array[i + 1]);
			newArr[index++] = t1.byteValue();
		}
		array = null;
		return newArr;
	}

	public static final String toHex(byte b) {
		return ("" + "0123456789ABCDEF".charAt(0xf & b >> 4) + "0123456789ABCDEF"
				.charAt(b & 0xf));
	}
	
	public static String post(String httpUrl,String content){
		StringBuffer sb = new StringBuffer();  
		try{
		URL url = new URL(httpUrl);   
		HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();   
		  
		   
		// //设置连接属性   
		httpConn.setDoOutput(true);// 使用 URL 连接进行输出   
		httpConn.setDoInput(true);// 使用 URL 连接进行输入   
		httpConn.setUseCaches(false);// 忽略缓存   
		httpConn.setRequestMethod("POST");// 设置URL请求方法   
		//String requestString = "客服端要以以流方式发送到服务端的数据...";   
		  
		   
		// 设置请求属性   
		// 获得数据字节数据，请求数据流的编码，必须和下面服务器端处理请求流的编码一致   
		//byte[] requestStringBytes = requestString.getBytes(ENCODING_UTF_8);   
		//httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);   
		//httpConn.setRequestProperty("Content-Type", "application/octet-stream");   
		//httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接   
		httpConn.setRequestProperty("Charset", "UTF-8");   
		//   
		//String name = URLEncoder.encode("黄武艺", "utf-8");  
		/*for(String key:params.keySet()){
			httpConn.setRequestProperty(key,params.get(key).toString());   
		}
		  */
		   
		// 建立输出流，并写入数据   
		OutputStream outputStream = httpConn.getOutputStream();   
		//outputStream.write(requestStringBytes);  
		
		PrintWriter pw=new PrintWriter(outputStream);
		//System.out.println(req.toString());
		pw.print(content);
		pw.flush();
		pw.close();
		outputStream.close();   
		// 获得响应状态   
		int responseCode = httpConn.getResponseCode();   
		  
		   
		if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功   
		// 当正确响应时处理数据    
		String readLine;   
		BufferedReader responseReader;   
		// 处理响应流，必须与服务器响应流输出的编码一致   
		 responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));   
		while ((readLine = responseReader.readLine()) != null) {   
		sb.append(readLine).append("\n");   
		}   
		responseReader.close();   
		//tv.setText(sb.toString());   
		}   
		} catch (Exception ex) {   
		ex.printStackTrace();   
		}   
		  return sb.toString();
	}
	
}
